package org.example.springoauth2.securitycommon.config.authenticate.grant.phone;

import lombok.AllArgsConstructor;
import org.example.springoauth2.securitycommon.service.SysUserService;
import org.example.springoauth2.securitycommon.util.SecurityUtil;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * @author hzq
 * @since 2021-09-12
 */
@AllArgsConstructor
public class PhoneAuthenticationProvider implements AuthenticationProvider {

    private final SysUserService sysUserService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        // PhoneAuthenticationToken authenticationToken = (PhoneAuthenticationToken) authentication;

        // 手机号
        String phone = SecurityUtil.obtainOpenidByPrincipal(authentication.getPrincipal());

        // 验证码
        String code = (String) authentication.getCredentials();

        UserDetails userDetails = sysUserService.loadUserByPhone(phone);

        PhoneAuthenticationToken token = new PhoneAuthenticationToken(userDetails);

        token.setDetails(authentication.getDetails());

        return token;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.isAssignableFrom(PhoneAuthenticationToken.class);
    }
}
